<?php

namespace App\Http\Controllers\Mobile\Index;
use Style,DB,Config;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\News\NewsImgExist;
use App\Models\News\News;
use App\Models\News\NewsCategory;

class NewsController extends CommonController{

    /**
     * 职场资讯列表
     * @param Request $request
     * @return mixed
     */
    public function news(Request $request){
        $request->only('id','search','class');

        $latelyNews = News::select('id','title','editorValue','style','readnum','updated_at')
            ->where(function($query) use ($request){
                if(!empty($request->class)){
                    $query->where('category',$request->class);
                }
                if(!empty($request->search)){
                    $query->where('title','like','%'.$request->search.'%');
                }
            })
            ->orderBy('updated_at','desc')->paginate(10);

        foreach($latelyNews as $k => $v){
            //有图片显示，无显示文本
            if(strlen($str = stristr($v->editorValue,'" title="',true))>0){
                $start = strpos($str,'<img src=');
                $end = strlen($str)-$start;
                $v->imgUrl = substr($str,$start+10,$end);
                $v->content = str_limit(strip_tags($v->editorValue),68);
            }else{
                $v->content = str_limit(strip_tags($v->editorValue),100);
            }
            $v->updated_at = substr($v->updated_at,0,10);
        }
        //讯息分类
        $firstClass = NewsCategory::select('id')->where('id',1)->first();
        $secondClass = NewsCategory::select('id','defectsname')->where('pid',$firstClass->id)->take(8)->get();
        $class=  $request->class;
        return Style::view('mobile.index.news',compact('latelyNews','secondClass','class'));
    }

    /**
     * 职场资讯详情
     * @param $id
     * @return mixed
     */
    public function newsInfo($id){
        $newsInfo = News::select('id','title','source','publisher','editorValue','style','readnum','updated_at')->where("id",$id)->first();
        //阅读量
        News::where("id",$id)->increment('readnum');
        if($newsInfo){
            return Style::view('mobile.index.newsInfo',compact('newsInfo'));
        }else{
            $exception = '没有找到相关数据';
            return Style::view('errors.mobile_404',compact('exception'));
        }
    }
}